<template>
  <el-container>
    <el-header>
      <h2>客服视频通话系统</h2>
    </el-header>
    <el-main>
      <el-row :gutter="20">
        <el-col :span="16">
          <!-- 视频通话区域 -->
          <el-card shadow="hover">
            <el-row :gutter="10">
              <el-col :span="12">
                <video ref="mine" autoplay width="100%"></video>
              </el-col>
              <el-col :span="12">
                <video ref="other" autoplay width="100%"></video>
              </el-col>
            </el-row>
            <!-- 结束通话按钮 -->
            <el-row :gutter="10" class="button-row">
              <el-col :span="12" class="center">
              </el-col>
            </el-row>
          </el-card>
          <!-- 在线用户展示区域 -->
          <el-card shadow="hover" class="user-list">
            <h3>求助用户</h3>
            <el-row :gutter="10">
              <el-col v-for="user in onlineUsers" :key="user.id" :span="6" class="center">
                <el-avatar :size="50" :icon="user.avatar"></el-avatar>
                <p>{{ user.name }}</p>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="8">
          <!-- 客服交互区域 -->
          <el-card shadow="hover">
            <el-form :inline="true" :model="form">
                  <el-divider></el-divider>
            当前客服:{{userName}}
            <el-divider></el-divider>
              <el-form-item label="发送给">
                <el-input v-model="to" placeholder="用户ID"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="startCall">开启视频通话</el-button>
                <el-button type="danger" @click="endCall">结束通话</el-button>
                <el-button type="success" block>语音通话</el-button>
                <el-button type="info" block @click="transferCall">转接</el-button>
              </el-form-item>
            </el-form>
            <div>我的频道: {{ mychannel }}</div>
          </el-card>
          <!-- 聊天窗口 -->
          <el-card shadow="hover" class="chat-window">
            <h3>聊天窗口</h3>
            <div class="chat-content">
              <div v-for="message in messages" :key="message.id" class="chat-message">
                <p><strong>{{ message.user }}:</strong> {{ message.text }}</p>
              </div>
            </div>
            <el-input
              type="textarea"
              v-model="newMessage"
              placeholder="输入消息"
              @keyup.enter="sendMessage"
            ></el-input>
            <el-button type="primary" @click="sendMessage" class="send-button">发送</el-button>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      userName:"",
      mychannel: "",
      to: "",
      self: "",
      peerConnection: null,
      socket: null,
      form: {
        to: ""
      },
      onlineUsers: [
        { id: 1, name: "用户1", avatar: "el-icon-user-solid" },
        { id: 2, name: "用户2", avatar: "el-icon-user-solid" },
        { id: 3, name: "用户3", avatar: "el-icon-user-solid" },
        { id: 4, name: "用户4", avatar: "el-icon-user-solid" }
      ],
      messages: [],
      newMessage: ""
    };
  },
  methods: {
    async handleIncomingOffer(data) {
      try {
        await this.peerConnection.setRemoteDescription(new RTCSessionDescription(data.offer));
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
        this.$refs.mine.srcObject = stream;
        stream.getTracks().forEach(track => this.peerConnection.addTrack(track, stream));
        const answer = await this.peerConnection.createAnswer();
        await this.peerConnection.setLocalDescription(answer);
        this.socket.send(JSON.stringify({ type: "answer", answer, to: data.from }));

        this.peerConnection.onicecandidate = (event) => {
          if (event.candidate) {
            this.socket.send(JSON.stringify({ type: "candidate", candidate: event.candidate, to: data.from }));
          }
        };

        this.peerConnection.ontrack = (event) => {
          this.$refs.other.srcObject = event.streams[0];
        };
      } catch (error) {
        console.error("Error handling offer:", error);
      }
    },
    async handleIncomingCandidate(data) {
      try {
        await this.peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
      } catch (error) {
        console.error("Error adding received ICE candidate:", error);
      }
    },
    sendKeFuCLMessage() {
    this.socket.send(JSON.stringify({"type":"KeFuCL","userName":this.userName}));
    },
    async startCall() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
        this.$refs.mine.srcObject = stream;
        stream.getTracks().forEach(track => this.peerConnection.addTrack(track, stream));
        this.peerConnection.onicecandidate = (event) => {
          if (event.candidate) {
            this.socket.send(JSON.stringify({ type: "candidate", candidate: event.candidate, to: this.to }));
          }
        };

        this.peerConnection.ontrack = (event) => {
          this.$refs.other.srcObject = event.streams[0];
        };
        const offer = await this.peerConnection.createOffer();
        await this.peerConnection.setLocalDescription(offer);
        this.socket.send(JSON.stringify({ type: "offer", offer: offer, to: this.to }));
      } catch (error) {
        console.error("Error starting call:", error);
      }
    },

    endCall() {
     // Stop all tracks in the local stream
      if (this.self) {
       this.self.getTracks().forEach(track => track.stop());
      }  
  },
    transferCall() {
      // Add your transfer call logic here
    },

    sendMessage() {
      if (this.newMessage.trim() !== "") {
        this.messages.push({ user: "我", text: this.newMessage, id: Date.now() });
        this.newMessage = "";
      }
    }
  },
  mounted() {
    this.userName = localStorage.getItem("username");
    this.peerConnection = new RTCPeerConnection();
    this.socket = new WebSocket("wss://192.168.2.18:8081/ws");
    this.socket.onopen = async()=>{
      // 用户连接之后发送至服务器加入缓存
      console.log("连接成功");
      this.socket.send(JSON.stringify({"type":"KeFu","userName":this.userName}));
    }
    this.socket.onclose = ()=>{
      console.log("连接关闭");
       this.sendKeFuCLMessage();
    }
    
    this.socket.onmessage = async (message) => {
      console.log(message.data);
      const data = JSON.parse(message.data);
      console.log(data);
      if (data.type === "offer") {
        this.handleIncomingOffer(data);
      } else if (data.type === "candidate") {
        this.handleIncomingCandidate(data);
      }
      if (data.type === "answer") {
        await this.peerConnection.setRemoteDescription(new RTCSessionDescription(data.answer));
      }
      if (data.type === "candidate") {
        await this.peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
      }
    };
  }
};
</script>

<style>
.el-header {
  background-color: #3a8ee6;
  color: #fff;
  text-align: center;
  padding: 20px;
  font-size: 24px;
}
.el-main {
  padding: 20px;
}
.el-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
video {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.user-list {
  margin-top: 20px;
}
.chat-window {
  margin-top: 20px;
}
.chat-content {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 10px;
}
.chat-message {
  margin-bottom: 10px;
}
.send-button {
  margin-top: 10px;
}
.center {
  text-align: center;
}
.button-row {
  margin-top: 10px;
}
</style>
